package oa.system

import grails.gorm.DetachedCriteria
import groovy.transform.ToString

import org.codehaus.groovy.util.HashCodeHelper
import grails.compiler.GrailsCompileStatic

@GrailsCompileStatic
@ToString(cache=true, includeNames=true, includePackage=false)
class AuthGroupAuth implements Serializable {

	private static final long serialVersionUID = 1

	AuthGroup authGroup
	Auth auth

	@Override
	boolean equals(other) {
		if (other instanceof AuthGroupAuth) {
			other.authId == auth?.id && other.authGroupId == authGroup?.id
		}
	}

	@Override
	int hashCode() {
	    int hashCode = HashCodeHelper.initHash()
        if (authGroup) {
            hashCode = HashCodeHelper.updateHash(hashCode, authGroup.id)
		}
		if (auth) {
		    hashCode = HashCodeHelper.updateHash(hashCode, auth.id)
		}
		hashCode
	}

	static AuthGroupAuth get(long authGroupId, long authId) {
		criteriaFor(authGroupId, authId).get()
	}

	static boolean exists(long authGroupId, long authId) {
		criteriaFor(authGroupId, authId).count()
	}

	private static DetachedCriteria criteriaFor(long authGroupId, long authId) {
		AuthGroupAuth.where {
			authGroup == AuthGroup.load(authGroupId) &&
			auth == Auth.load(authId)
		}
	}

	static AuthGroupAuth create(AuthGroup authGroup, Auth auth, boolean flush = false) {
		def instance = new AuthGroupAuth(authGroup: authGroup, auth: auth)
		instance.save(flush: flush)
		instance
	}

	static boolean remove(AuthGroup rg, Auth r) {
		if (rg != null && r != null) {
			AuthGroupAuth.where { authGroup == rg && auth == r }.deleteAll()
		}
	}

	static int removeAll(Auth r) {
		r == null ? 0 : AuthGroupAuth.where { auth == r }.deleteAll() as int
	}

	static int removeAll(AuthGroup rg) {
		rg == null ? 0 : AuthGroupAuth.where { authGroup == rg }.deleteAll() as int
	}

	static constraints = {
	    authGroup nullable: false
		auth nullable: false, validator: { Auth r, AuthGroupAuth rg ->
			if (rg.authGroup?.id) {
				if (AuthGroupAuth.exists(rg.authGroup.id, r.id)) {
				    return ['roleGroup.exists']
				}
			}
		}
	}

	static mapping = {
		id composite: ['authGroup', 'auth']
		version false
	}
}
